package com.shaliy.collector.controller;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.shaliy.collector.entity.UserEntity;
import com.shaliy.collector.service.UserService;

@RestController
public class UserController {
	
	@Autowired
    private StringRedisTemplate template;

	@Autowired
	private UserService userService;
	
    /**
     *	 判断key是否存在
     */
    @RequestMapping("/redis/hasKey/{key}")
    public Boolean hasKey(@PathVariable("key") String key) {
        try {
            return template.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 	校验用户名密码，成功则返回通行令牌
     */
    @RequestMapping("/checkUsernameAndPassword")
    private String checkUsernameAndPassword(String phone, String password) {
    	
    	UserEntity user = userService.findOne(phone);
    	if(user==null) {
    		return null;
    	}
        //通行令牌
        String flag = null;
        if (user.getPhone().equals(phone) && user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            //用户名+时间戳（这里只是demo，正常项目的令牌应该要更为复杂）
            flag = phone + System.currentTimeMillis();
            //令牌作为key，存用户id作为value（或者直接存储可暴露的部分用户信息也行）设置过期时间（我这里设置3分钟）
            template.opsForValue().set(flag, "1", (long) (3 * 60), TimeUnit.SECONDS);
        }
        return flag;
    }

    /**
     * 	跳转登录页面
     */
    @RequestMapping("/loginPage")
    private ModelAndView loginPage(String url) {
        ModelAndView modelAndView = new ModelAndView("login");
        modelAndView.addObject("url", url);
        return modelAndView;
    }

    /**
     * 	跳转注册页面
     */
    @RequestMapping("/signInPage")
    private ModelAndView signInPage(String url) {
        ModelAndView modelAndView = new ModelAndView("signIn");
        modelAndView.addObject("url", url);
        return modelAndView;
    }
    
    @RequestMapping("/signIn")
    private ModelAndView signIn(String phone,String username, String password,String url) {
    	
    	userService.save(phone, username, DigestUtils.md5DigestAsHex(password.getBytes()));
    	ModelAndView modelAndView = new ModelAndView("login");
    	modelAndView.addObject("url", url);
    	return modelAndView;
    }
    
    /**
     * 	页面登录
     */
    @RequestMapping("/login")
    private String login(HttpServletResponse response, String phone, String password, String url) {
        String check = checkUsernameAndPassword(phone, password);
        if (!StringUtils.isEmpty(check)) {
            try {
                Cookie cookie = new Cookie("accessToken", check);
                cookie.setMaxAge(60 * 3);
                //设置访问路径
                cookie.setPath("/");
                response.addCookie(cookie);
                //重定向到原先访问的页面
                response.sendRedirect(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        return "登录失败";
    }
}
